<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8"/>
<title>edit-servers</title>
<link rel="stylesheet" href="../assets/css/bootstrap-spacelab.css" />
<link rel="stylesheet" href="../assets/css/base.css?t=20130516173114" />
<link rel="stylesheet" href="../assets/css/validationEngine.jquery.css" type="text/css"/>

  <!-- template
    ================================================== -->
    <script id="t_a" type="text/html">
    	<% var json = json || {}; var upload_direction = json.upload_direction || {}; %>
				<form class="form-horizontal" id="form" onsubmit="return false;">
					 <fieldset>
					 	<br />
                        <div class="control-group">
                            <label class="control-label" for="name"> 自定义服务器组名： </label>
                            <div class="controls">
                                <input type="text" class="validate[required,custom[onlyLetterNumber]] text-input"  name="name" id="name" value="<%= json.name || '' %>" >
                                <p class="help-block">服务器组名不能为空和数字，不能含有空格</p>
                            </div>
                        </div>
						
                        <div class="control-group">
                            <label class="control-label" for="desc"> 备注：</label>
                            <div class="controls">
                                <textarea name="desc" id="desc" rows="3"  value="<%= json.desc || '' %>" ><%= json.desc || '' %></textarea>
								<p class="help-block">可选的备注信息</p>
                            </div>
                        </div>					
						
                        <div class="control-group">
                            <label class="control-label" for="mailtype"> 接受报警类型：</label>
                            <div class="controls">
                                <select name="mailtype" id="mailtype">
                                	<option value="1" <%= json.mailtype == 1 && 'selected' %> >不接收</option>
                    				<option value="2" <%= json.mailtype == 2 && 'selected' %> >普通报警</option>
                    				<option value="3" <%= json.mailtype == 3 && 'selected' %> >严重报警</option>
                    				<option value="4" <%= json.mailtype == 4 && 'selected' %> >所有报警</option>
                                </select>
								<a href="#" id="mailtype_tips" class="help-inline" rel="tooltip" data-original-title="提示：<br>如果你希望管理两组服务器，一组报警，一组不报警，<br>可以创建一个组为不接收，另一个组为报警。<br>然后将自己所在的两个用户组分别加入这两个组即可；<br>或者直接在一个用户组中设置报警类型为不接收。"><i class="icon-info-sign"></i></a>
								<p class="help-block">（辅助选项）当用户选项为“按用户组所属服务器设置”时，则按此设置报警</p>
                            </div>
                        </div>													
																													
                        <div class="form-actions">
                            <button class='btn btn-info' name="submit"> 保存 </button>
							&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
							<button class='btn' name="return"> 返回 </button>
                            <input type="reset" style="display:none;">
                        </div>
				</fieldset>
			</form>
			
    </script>

  <!-- template
    ================================================== -->
    <script id="t_b" type="text/html">
         <%
            var empty = function (obj){
            				for (var name in obj) {
            					return false;
            				}
            				return true;
            			};
         %>  
    	<div style="height:30px;padding-bottom:10px;">
        	<p>
            	<label class="checkbox inline">
                	<input type="checkbox" name="override_set" <%= override_set ? 'checked' : '' %> /> &nbsp;覆盖服务器的监控项设置
            	</label>
        	</p>	
    	</div>		   	
        <ul class="accordion" id="accordion">
            <% for (var i in json) { var item = json[i] || {}, arr = map[i] || []; %>
			<li class="accordion-group">
				<i class="icon40-<%= i %>"></i>
            <div class="accordion-heading">
                <h5>
					<label class="checkbox inline">
                            <input type="checkbox" name="<%= i %>" title="<%= empty(item) ? '不可用' : '全选' %>"  <%= empty(item) ? 'disabled' : '' %> <%= isAll[i] ? 'checked' : '' %> />&nbsp;<%= arr && arr[0] %> 
                    </label>
					&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
					<% if(!empty(item)){ %>
						<a data-toggle="collapse" data-parent="#accordion" href="#<%= i %>">明细  ▼</a>	
					<% } %>
				</h5>
				<p class="help-block"><%= arr && arr[1] %></p>
            </div>
			
            <div class="accordion-body collapse" id="<%= i %>">
            	<% for(var j in item ) { %>
                        <label class="checkbox inline">
                            <input type="checkbox" data-all="<%= i %>" name="<%= j %>" value="<%= item[j] %>" <%= item[j]*1 && 'checked' %> />&nbsp;<%= j %>
                        </label>	
				<% } %>
            </div>
			</li>
            <% } %>
        </ul>
		
    </script>
	
 <!-- template
    ================================================== -->
    <script id="t_c" type="text/html">
        <table class="table table-striped table-bordered table-condensed">
            <thead>
                <tr>
					<th> 用户组名 </th>
                    <th> 描述 </th>
					<th> 成员 </th>
					<th> 是否隶属此组 </th>
                    <th> 操作 </th>					
                </tr>
            </thead>
            <tbody>
                <%var json = json || {};
				 for (var i in json) {
                	var item = json[i] || {};
					var arr = item[1] || [];
					var ischecked = ischecked || {};
					 %>
                <tr>
                    <td>
                        <%= i %>
                    </td>
                    <td>
                        <%= item[0] %>
                    </td>
                    <td>
						<% for (var j = 0; j < arr.length; j++ ) { %> 
                        	<%= j ? ', ' + arr[j] : '' + arr[j] %>
						<% } %> 
                    </td>					
                    <td>
						<i class="<%= ischecked[i] ? 'icon-ok' : '' %>"></i>
						<label class="checkbox inline" style="display:none;">
                            <input type="checkbox" name='group' value="<%= i %>" <%= ischecked[i] ? 'checked' : '' %> />
                    	</label>
                    </td>					
                    <td>
                        <button class="btn" data-mark="<%= ischecked[i] ? 1 : 0 %>"  title="<%= ischecked[i] ? '从该组移除' : '添加到该组' %>">
                        	<i class="<%= ischecked[i] ? 'icon-minus' : 'icon-plus' %>"></i>
						</button>
                    </td>  					
                </tr>
                <% } %>
            </tbody>
        </table>
				
    </script>	
	
<style>
#monitor_option{
	padding:0 30px;
}	
#monitor_option ul li{
	padding:10px 0 10px 10px;
	margin-bottom:5px;
}
#monitor_option ul li h5{
	margin-bottom:5px;
}
#monitor_option ul li > div:last-child{
	padding-left:70px;
}

#monitor_option ul li i {
	float:left; margin-right:30px;
}	

label[class="checkbox inline"]{
	display:inline-block;
	width:320px;
}
.checkbox.inline + .checkbox.inline{
	margin-left:0;
}

#mailtype_tips{
	display:none;
}
</style>

</head>
<body>
    <header>
        <h1><span id="title">修改自定义服务器组  &nbsp;&nbsp;&gt;&gt;</span>&nbsp;&nbsp;<span id="serversName"></span></h1>
        <div class="row" id="toolbar">
                <div class="box_1">
                    <button class="btn" id="info">
                        <i class="icon-info-sign"></i> 信息
                    </button>					
                </div>
				
                <div class="btn-group" style="display:none;">
                    <button class="btn">
                        	操作
                    </button>
                    <button class="btn dropdown-toggle" data-toggle="dropdown">
                        <span class="caret"></span>
                    </button>
                    <ul class="dropdown-menu">
                        <li><a href="#" id="notification"></a></li>
                    </ul>
                </div>
        </div>
    </header>	
	
    <div id="mainbody">
        <div class="tabbable">
            <ul class="nav nav-tabs">
                <li class="active">
                    <a href="#general" data-toggle="tab">基本信息</a>
                </li>
                <li>
                    <a href="#in_group" data-toggle="tab">成员用户组</a>
                </li>
                <li>
                    <a href="#monitor_option" data-toggle="tab">监控项</a>
                </li>
            </ul>
            <div class="tab-content">
                <div class="tab-pane active" id="general">
                </div>
                <div class="tab-pane" id="in_group">
                </div>
                <div class="tab-pane" id="monitor_option">
                </div>
            </div>
        </div>
    </div>
	

  <!-- 弹出对话框
    ================================================== -->
<div class="modal fade" id="modal">
  <div class="modal-header">
    <a class="close" data-dismiss="modal">×</a>
    <h3>OK</h3>
  </div>
  <div class="modal-body">
  	
  </div>
  <div class="modal-footer">
    <a href="#" class="btn" name="return">返回</a>
    <a href="#" class="btn btn-info" id="nextEdit">继续修改</a>
  </div>
</div>


  <!-- js part
    ================================================== -->
<script src="../assets/js/library/jquery-1.7.1.js"></script>
<script src="../assets/js/library/bootstrap.min.js"></script>
<script src="../assets/js/library/template.js"></script>
<script src="../assets/js/library/jquery.validationEngine-en.js"></script>
<script src="../assets/js/library/jquery.validationEngine.js"></script>
<script src="../assets/js/helper.js?t=20130516173114"></script>
<script src="../assets/js/doc.js?t=20130516173114"></script>	
<script>
$(function(){
	var smartMad = window.smartMad = window.smartMad || {};
	var domain = domainURI();
    var version = urlParams('version');
	
    var _url = 'http://' + domain + '/mmsapi' + version;
	
	var serversName = urlParams('name') || '';
	
	//判断是修改还是创建
	var submitUrl = _url + (serversName ? '/update/serverGroup/@self/' + serversName : '/create/serverGroup/@self');
	
	var submitSuccessCall = function(){
		$('#modal').modal('show').find('.modal-body').html('添加成功!');
	};
	
	////////////////////////////////////////////////////
	//常规选项设置
	////////////////////////////////////////////////////
	var generalConf = {
		url: _url + '/get/servergroup/@self/' + serversName
	};	
	var generalCall = function(e,json){
		var $th = $(this), data, html;
		
		//$th.html(JSON.stringify(json));return;
        ///////////////////////////////////////////////
		
		json.name = serversName;
		
		smartMad.json = json;
		smartMad.override_set = json.override_set*1;
		
		///////////////////////////////////////////////
        data = {
            json: json
        };
        
        ///////////////////////////////////////////////
        
        html = template('t_a', data);
        $th.html(html);
		
		if(serversName){
			$('#in_group').bind('ajax.success', inGroupCall).getData(inGroupConf);
			$('#monitor_option').trigger('ajax.success',[json.monitoritem]);			
		}
		
		///////////////////////////////////////////////
		//表单验证
		$('#form').validationEngine();		

	};
	
	////////////////////////////////////////////////////
	//usergroup
	////////////////////////////////////////////////////
	var inGroupConf = {
		url: _url + '/get/usergroup/@all'
	};	
    var inGroupCall = function(e, json){
		var $th = $(this), data, html;
		var ischecked = {};
		var membergroup = (smartMad.json && smartMad.json.membergroup || '').split('|');		
		
		//$th.html(JSON.stringify(json));return;
        ///////////////////////////////////////////////

		for(var i; i = membergroup.shift(); ){
			ischecked[i] = 1;
		}
		
		///////////////////////////////////////////////
		
        data = {
            json: json,
			ischecked: ischecked
        };
        
        ///////////////////////////////////////////////
        
        html = template('t_c', data);
        $th.html(html);	
		
		///////////////////////////////////////////////
		
		$th.find('table').delegate('button','click',function(){
			var $th = $(this);
			var mark = $th.attr('data-mark') * 1;
			if(mark){
				$th.find('i').removeClass('icon-minus').addClass('icon-plus');
				//$th.find('span').html('添加到该组');
				$th.parent().prev().find('i').toggleClass('icon-ok').end().find(':checkbox').attr('checked',false);
				$th.attr('data-mark',0).attr('title','添加到该组');
			}else{
				$th.find('i').removeClass('icon-plus').addClass('icon-minus');
				//$th.find('span').html('从该组移除');
				$th.parent().prev().find('i').toggleClass('icon-ok').end().find(':checkbox').attr('checked',true);				
				$th.attr('data-mark',1).attr('title','从该组移除');
			}
			
		});	
	};		
	
	////////////////////////////////////////////////////
	//监控选项
	////////////////////////////////////////////////////	
	var monitorOptionConf = {
		url: _url + '/get/monitoritem/@all/'
	};	
	var monitorOptionCall = function(e,json){
		var $th = $(this), data, html, isAll = {};
		
		//$th.html(JSON.stringify(json));return;
        ///////////////////////////////////////////////
		for(var i in json){
			var item = json[i];
			isAll[i] = true;
			for(var j in item){
				if(!(item[j]*1)){
					isAll[i] = false;
					break;
				}
			}
		}
		
        ///////////////////////////////////////////////
        data = {
            json: json,
			isAll: isAll,
			map: smartMad.monitorOptionMap,
			override_set:smartMad.override_set
        };
        
        ///////////////////////////////////////////////
        
        html = template('t_b', data);
        $th.html(html);	
		
		////////////////////////////////////////////////
		
		$th.delegate(':checkbox[title="全选"]','click',function(){
			var $th = $(this);
			var name = $th.attr('name');
			$(':checkbox[data-all="' + name + '"]').attr('checked',!!$th.attr('checked'));
		});	
		
		$th.delegate(':checkbox[data-all]','click',function(){
			var $th = $(this);
			var all = $th.attr('data-all');
			
			if($th.attr('checked') && $(':checkbox[data-all="' + all + '"]').length == $(':checkbox[data-all="' + all + '"]:checked').length){
				$('input[type="checkbox"][name="' + all + '"]').attr('checked',true);
			}else{
				$(':checkbox[name="' + all + '"]').attr('checked',false);
			}
		});			
		
	};	
	
	////////////////////////////////////////////////////////
	//提交保存
	////////////////////////////////////////////////////////
    $('#mainbody').delegate('button[name="submit"]', 'click', function(){
        var conf = {
            data: {},
        };
		
		//表单验证
		if(!$('#form').validationEngine('validate')){
			return;
		}		
		
		if(!serversName){
			conf.success = submitSuccessCall;
		} 
		
		smartMad.serversName = $('[name="name"]').val();
		
		var general_json = {'name':1,'mailtype':1,'desc':1};
		
		var group = '';
		var monitoritem = '';
		
		for (var i in general_json){
			conf.data[i] = $('[name="' + i + '"]').val();
		}
		
		$(':checkbox[name="group"]:checked').each(function(){
			group += $(this).val() + '|'; 
		});
		
		conf.data['membergroup'] = group;
		
		$('#monitor_option h5 :checkbox').each(function(i){
			var name = $(this).attr('name');
			monitoritem += i != 0 ? '#' + name : name;
			$(':checkbox[data-all="' + name + '"]').each(function(){
				var $th = $(this);
				monitoritem += '|';
				monitoritem += $th.attr('name');
				monitoritem += ':';
				monitoritem += !!$th.attr('checked') ? '1' : '0';
			});
		});
		
		conf.data['monitoritem'] = monitoritem;
		
		conf.data['override_set'] = $(':checkbox[name="override_set"]').attr('checked') ? 1 : 0;
		
		//console.log(JSON.stringify(conf));
		
        conf.url = submitUrl;
		
        $(this).postData(conf);
    });
	
	/////////////////////////////////////////////////////
	
	$('body')
	.delegate('[name="return"]', 'click', function(){
	    location.href = 'serversList.html?version=' + version;
	 })
	 .delegate('#nextEdit','click',function(){
	 	location.href = 'editServers.html?name=' + smartMad.serversName + '&version=' + urlParams('version');
	 });
	 
	 
	 $('select[name="mailtype"]').live('change',function(){
	 	$('#mailtype_tips').show().tooltip({
			placement:'right',
			trigger:'hover'
		});
	 });
	 
	////////////////////////////////////////////////////////
	//init
	////////////////////////////////////////////////////////
	
    if (serversName) {
        $('#serversName').text(serversName);
        
        $('#general').bind('ajax.success', generalCall).getData(generalConf);
        
        $('#in_group').bind('ajax.success', inGroupCall);
		
        $('#monitor_option').bind('ajax.success',monitorOptionCall);
				
    }else{
		 $('#title').text('添加自定义服务器组');
		 $('#general').bind('ajax.success', generalCall).trigger('ajax.success',[{}]);
		 $('#in_group').bind('ajax.success', inGroupCall).getData(inGroupConf);
		 $('#monitor_option').bind('ajax.success',monitorOptionCall).getData(monitorOptionConf);
	}

});
</script>
</body>
</html>
